package edu.clarkson.ee368.spring2012.coreservices;

import java.io.IOException;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(
	filterName="authenticationFilter",
	urlPatterns="/*",
	dispatcherTypes={DispatcherType.REQUEST}
)
public class AuthenticationFilter implements Filter {
	
//	private static final String NOT_AUTHENTICATED_MESSAGE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
//			"<error message=\"not authenticated\"/>";
//
//	@EJB
//	private AccountDAO accountDAO;
//	
	@Override
	public void destroy() {
		// No cleanup needed yet
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		chain.doFilter(request,  response);
//			HttpServletRequest req = (HttpServletRequest)request;
//			HttpServletResponse resp = (HttpServletResponse)response;
//			String servletPath = req.getServletPath();
//			if ("/accounts".equals(servletPath)) {
//				chain.doFilter(request, response);
//			}
//			else {
//				HttpSession session = req.getSession();
//				Integer accountId = (Integer) session.getAttribute("accountId");
//				if (accountId == null) {
//					writeError(resp);
//				}
//				else {
//					Account acct = accountDAO.getAccountFromId(accountId);
//					if (acct == null) {
//						session.removeAttribute("accountId");
//						writeError(resp);
//					}
//					else {
//						chain.doFilter(request, response);
//					}
//				}
//			}			
	}

//	private void writeError(HttpServletResponse resp) throws IOException {
//		resp.setContentType("text/xml");
//		resp.setContentLength(NOT_AUTHENTICATED_MESSAGE.length());
//		resp.getWriter().println(NOT_AUTHENTICATED_MESSAGE);
//		resp.getWriter().flush();
//		resp.getWriter().close();
//	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
